<template>
  <div>
    <div class="h5videowrapper h5container" :id="h5containerid" @dblclick="fullScreen()">
      <video
        v-show="!showError && protocol == VideoProtocols.WEBSOCKET"
        class="h5video"
        :id="'h'+index"
        autoplay
        webkit-playsinline
        playsinline
      >
      </video>
      <!-- <canvas v-show="!showError && protocol == VideoProtocols.WEBSOCKET" class="h5canvas" width="1920" height="1280" :id="h5videoid" ></canvas> -->
      <!-- 错误信息 -->
      <div v-if="showError" class="error-video">
        <span>{{ errorMessage }}</span>
      </div>
      <!-- 悬浮按钮 -->
      <div class="operation">
        <!-- <div class="close operation-item">关闭</div> -->
        <div class="screenshot operation-item" @click="capaturePicture()">抓图</div>
      </div>
    </div>
    <!-- <button @click="wmplayer()">点击播放</button> -->
    <!-- <button @click="myclose()">关闭播放</button>
    <button @click="capaturePicture()">点击截图</button> -->
    

    <div id="showPic" v-show="show_panel">
      <CanvasEdt :cvsData="cvsData"></CanvasEdt>
        <!-- <canvas id="showincvs"></canvas> -->
    </div>
  </div>
</template>
<script>
import { H5sPlayerRtc } from "@/utils/h5splayer.js";
import md5 from "js-md5";
import axios from "axios";
import CanvasEdt from '@/components/CanvasEdt'
export default {
  name: "liveplayer",
  components: {CanvasEdt},
  props: [
    "h5videoid",
    "col",
    "row",
    "h5controlsid",
    "h5containerid",
    "setRows",
    "selectRow",
    "selectCol",
    "playerUrl",
    "index"
  ],
  
  data() {
    return {
      show_panel: false,   // 画板是否显示
      signature: "UOv9u5hhF6G+RC97Bs3k8A==",
      time: 15000, // 时间间隔默认是15秒
      resid: 16779777, // 资源id
      begintime: null, // 开始时间
      endtime: null, // 结束时间
      fileid: null, // 文件id
      settime: null, // seek time value
      videoid: this.h5videoid,
      canvasplay: null,
      videoHandler: null,
      videoname: "",
      video: null,
      container: null,
      isStop: false, // 是否暂停
      isFull: false, // 是否全屏
      ability: 1, // 能力集
      videoControls: null,
      showControls: false,
      showError: false,
      saturation: 1,
      hue: 360,
      brightness: 1,
      contrast: 1,
      host: null,
      currentVideoMode: 1, // 默认是实时预览模式
      currentPlayStatus: 0, // 当前的播放状态 0：未播放
      currentSpeed: 0, // 当前的播放速度
      winIndex: 0, // 当前窗口的Index
      isJumpProgress: true, // 进度条跳转
      lastestPosition: 0, //
      currentPosition: 0,
      camera_view: null,
      errorMessage: "",
      videoInterval: null, // 重连interval
      streamType: 0, // 0： 主码流, 1: 子码流
      AbilityType: {
        MAINSTREAM: 1, // 主码流值
        SUBSTREAM: 2 // 子码流值
      },
      VideoProtocols: {
        RTSP: 0, // RTSP协议播放
        OCX: 1, // OCX播放, 用于ie,在不是ie的浏览器上不使用
        WEBRTC: 2, // webrtc进行播放
        WEBSOCKET: 3 // WEBSOCKET      3:ws 5:wss
      },
      protocol: 3, // 默认为websocket协议  3:ws 5:wss
      VideoMode: {
        REALPLAY: 1, // 实时预览模式
        BACKPLAY: 2 // 回放模式
      },
      PlayStaus: {
        NOTPLAY: 0, // 未播放
        PLAYING: 1, // 播放中
        PAUSE: 2 // 暂停
      },

      ErrorMsgInfo: {
        "-1": "错误码为1",
        "1": "Websocket连接失败",
        "2": "连接超时",
        "3": "没有接受到心跳包",
        "4": "播放异常",
        "5": "断线重连中...",
        "6": "解码异常, 正在重新打开"
      },
      ErrorMsgType: {
        COMMONERROR: "-1",
        WSCONNECTIONERROR: "1",
        WSCONNECTIONTIMEOUT: "2",
        WSNOHEART: "3",
        PLAYERROR: "4",
        WSRECONNECT: "5",
        PARSEDATAERROR: "6"
      },
      h265Player: null,
      remoteVideoId:null,
      cvsData:null,
    };
  },
  watch: {
    playerUrl(newUrl,oldUrl){
      if(typeof newUrl !== 'undefined' && newUrl!==null && newUrl.length>0 && newUrl!==oldUrl){
        this.wmplayer();
      }
    },
    videoHandler() {
      if (!this.videoHandler) {
        // this.removeVideoEventListener(); //感觉没必要
        this.videoname = "";
      }
    },
    setRows: {
      handler() {
        this.currentWindowSizeChange();
      }
    }
  },

  mounted() {
    // console.log("holt:", Player);
    // this.$root.eventHub.$on('destory', () => {
    //   this.handleDisConnect()
    // })
    // this.addVideoEventListener()
  },
  beforeDestroy() {
    if (this.videoHandler !== null) {
      this.videoHandler.disconnect();
      this.videoHandler = null;
    }
  },
  methods: {
    //截图底层实现
    _capaturePicture() {
      var remoteVideoId = this.remoteVideoId = document.getElementById("h"+this.index);
      console.log("截图:", this.remoteVideoId);
      if (this.remoteVideoId) {
      //   const canvas = document.createElement("canvas"); //document.getElementById("showincvs"); //
      //   const ctx = canvas.getContext("2d");
      //   canvas.width = this.remoteVideoId.clientWidth;
      //   canvas.height = this.remoteVideoId.clientHeight;
      //   console.log("画布宽高度：",canvas.width,canvas.height);
      //   ctx.drawImage(
      //     this.remoteVideoId,
      //     0,
      //     0,
      //     canvas.width,
      //     canvas.height
      //   );
      this.cvsData = remoteVideoId;
      this.show_panel = true
        // this.saveImage(canvas);
        // console.log("canvas格式：",canvas.toDataURL("image/png"));
      }
      // document.getElementById("showPic").style.cssText="display:block";//显示
    },
    // 保存图片
    saveImage(canvas) {
      const image = canvas
        .toDataURL("image/png");
        // .replace("image/png", "image/octet-stream");
      this.saveFile(image, "file_" + new Date().getTime() + ".png");
    },

    // 保存文件
    saveFile(data, filename) {
      console.log("data格式：",data);
      const save_link = document.createElement("a");
      save_link.href = data;
      save_link.download = filename;
      save_link.click();
    },
    myclose() {
      if (this.videoHandler !== null) {
        this.videoHandler.disconnect();
        this.videoHandler = null;
      }
    },
    wmplayer() {
      // console.log("Player", Player);
      this.getStreamUrlAndPlay(111);
    },
    getStreamUrl(data) {
      let url1 = "http://49.4.12.100:10012";
      let getStreamUrl = "/openapi/video/getStreamUrl";
      var token = md5(getStreamUrl + data);
      return axios.post(url1 + getStreamUrl + "?token=" + token, data);
    },
    // 当前窗口发生变化
    currentWindowSizeChange() {
      let streamType = this.streamType;
      streamType = this.getStreamType();
      // 判断跟当前的码流类型是否一致, 不一致的情况下再切换视频流
      if (this.streamType != streamType) {
        this.streamType = streamType;
        this.switchStreamByType(this.streamType);
      }
    },

    // 添加视频屏幕的监听事件
    addVideoEventListener() {
      this.container = document.getElementById(this.h5containerid);
      this.container.addEventListener("mouseover", e => {
        if (this.videoHandler) {
          this.showControls = true;
        }
      });
      this.container.addEventListener("mouseout", e => {
        this.showControls = false;
      });
    },

    // 删除视频屏幕的监听事件
    removeVideoEventListener() {
      console.log("removeEventListener");
      this.container.removeEventListener("mouseover", e => {
        console.log("remove mouseover");
      });
      this.container.removeEventListener("mouseout", e => {
        console.log("remove mouseout");
      });
    },

    // 播放视频
    playVideo(host, camera_view = null) {
      this.showError = false;
      this.host = host;
      if (this.videoHandler == null) {
        if (this.protocol === this.VideoProtocols.WEBRTC) {
          const confk = this.setWebrtcConf(this.h5videoid, host, camera_view);
          this.camera_view = camera_view;
          this.webrtcPlayConnect(confk);
        } else if (this.protocol === this.VideoProtocols.WEBSOCKET) {
          const confk = this.setWebsocketConf(this.h5videoid, host);
          this.websocketPlayConnect(confk);
        }
      } else {
        if (this.protocol === this.VideoProtocols.WEBRTC) {
          this.videoHandler.disconnect();
          this.videoHandler = null;
          const confk = this.setWebrtcConf(this.h5videoid, host, camera_view);
          this.camera_view = camera_view;
          this.webrtcPlayConnect(confk);
        } else if (this.protocol === this.VideoProtocols.WEBSOCKET) {
          this.videoHandler.disconnect();
          this.videoHandler = null;
          const confk = this.setWebsocketConf(
            this.h5videoid,
            host,
            camera_view
          );
          this.camera_view = camera_view;
          this.websocketPlayConnect(confk);
        }
      }
    },

    // webrtc建立连接播放
    webrtcPlayConnect(confk) {
      try {
        this.videoHandler = new H5sPlayerRtc(confk);
        // 建立连接的回调函数
        const callback = state => {
          // 如果状态为-1, 则出现异常的情况
          if (state === -1) {
            this.setErrorMessage(this.videoname, -1);
            this.handleDisConnect();
          }
        };
        this.videoHandler.connect(callback);
      } catch (e) {
        this.setErrorMessage(this.videoname, "-1");
        this.handleDisConnect();
      }
    },

    websocketPlayConnect(confk) {
      confk.domId = "h"+this.index;
      console.log("websocketPlayConnect信息:", confk);
      this.videoHandler = new Player({
        domId: confk.domId,
        videoEnabled: true,
        onErrorFun: error => {
          this.setErrorMessage(this.videoname, error);
        },
        onReconnect: () => {
          if (this.currentVideoMode === this.VideoMode.REALPLAY) {
            this.setErrorMessage(this.videoname, this.ErrorMsgType.WSRECONNECT);
          }
        },
        onWsSuccess: () => {
          this.wsConnectSuccess();
        },
        onPlaying: () => {
          if (this.currentVideoMode === this.VideoMode.BACKPLAY) {
            this.DoRemoteFileSpeed(this.currentSpeed);
          }
        },
        onbackTimestamp: (nPos, bEnd) => {
          if (this.currentVideoMode === this.VideoMode.BACKPLAY) {
            this.websocketBackTimestamp(nPos, bEnd);
          }
        }
      });

      this.videoHandler.play(confk.url);
    },

    websocketBackTimestamp(pos, bEnd) {
      // 用户进度条移动, 以及跳转到下一时间片
      const nPos = this.settime + pos - this.lastestPosition;
      this.currentPosition = pos;

      const data = {
        nWndIndex: this.winIndex,
        nPos: nPos,
        bEnd: bEnd
      };

      // 当前的nPos在改时间段的结尾, 关闭连接

      this.$emit("back-timestamp", data);
    },

    canvasSizeChange() {
      const canvas = document.getElementById(this.h5videoid);
      if (this.protocol == this.VideoProtocols.WEBSOCKET) {
        if (this.videoHandler) {
          this.videoHandler.setVideoSize(canvas.width, canvas.height);
        }
      }
    },

    /**
     * 根据资源id获取该资源的实时视频流的url, 并进行播放
     */
    DoRealPlayStart1(resid, name, ability, callback) {
      this.showError = false;
      this.resid = resid;
      this.videoname = name;
      this.ability = ability;
      this.streamType = this.getStreamType();
      this.currentVideoMode = this.VideoMode.REALPLAY;
      this.getStreamUrlAndPlay(resid, callback);
    },

    /**
     * 根据文件id获取该资源的回放视频流的url, 并进行播放
     */
    DoBackPlayStart(
      resid,
      name,
      begintime,
      endtime,
      fileid,
      settime,
      winIndex
    ) {
      this.showError = false;
      this.resid = resid;
      this.videoname = name;
      this.begintime = begintime;
      this.endtime = endtime;
      this.winIndex = winIndex;
      this.settime = settime;

      this.currentVideoMode = this.VideoMode.BACKPLAY;
      if (this.fileid != fileid) {
        this.fileid = fileid;
        this.lastestPosition = 0;
        this.getFileUrlAndPlay(this.fileid);
      } else {
        this.lastestPosition = this.currentPosition;
        this.DoRemoteFileSeekTo(this.settime);
        this.DoRemoteFileSpeed(this.currentSpeed);
      }
    },

    DoRemoteFilePause(pause) {
      // 1: 暂停 0:恢复
      if (
        this.videoHandler &&
        this.protocol === this.VideoProtocols.WEBSOCKET
      ) {
        this.videoHandler.pause(pause);

        if (pause === 1) {
          this.currentPlayStatus = this.PlayStaus.PAUSE;
        }
        if (pause === 0) {
          this.currentPlayStatus = this.PlayStaus.PLAYING;
        }
      }
    },

    DoRemoteFileSeekTo(settime) {
      if (this.videoHandler) {
        this.videoHandler.seekTo(settime);
      }
    },

    DoRemoteFileSpeed(value) {
      if (this.videoHandler) {
        this.videoHandler.speed(value);
      }
    },

    // 单帧播放
    DoRemoteFileSingleFrame() {
      if (this.currentPlayStatus === this.PlayStaus.NOTPLAY) {
        return;
      }

      if (this.currentPlayStatus === this.PlayStaus.PLAYING) {
        this.DoRemoteFilePause(1);
      }

      if (
        this.currentPlayStatus === this.PlayStaus.PAUSE &&
        this.videoHandler
      ) {
        this.videoHandler.singleFrame();
      }
    },

    DoRemoteBackPlaySlow() {
      if (this.currentSpeed <= -3) {
        return;
      }
      this.currentSpeed -= 1;
      if (this.videoHandler) {
        this.videoHandler.speed(this.currentSpeed);
      }
    },

    DoRemoteBackPlayFast() {
      if (this.currentSpeed >= 3) {
        return;
      }
      this.currentSpeed += 1;
      if (this.videoHandler) {
        this.videoHandler.speed(this.currentSpeed);
      }
    },

    getWindowPlayStatus() {
      return this.currentPlayStatus;
    },

    getCurrentSelectId() {
      return this.resid || this.fileid;
    },

    /**
     * 获取流媒体类型, 根据当前窗口, 分为单窗口主码流和多窗口子码流
     * 如果该视频只支持其中一种码流类型, 窗口的切换就起不到作用了, 根据
     * 视频的主子码流类型返回视频流类型
     */
    getStreamType() {
      let streamType = 0;
      if (this.setRows > 1) {
        if (this.ability & this.AbilityType.SUBSTREAM) {
          streamType = 1;
        } else if (this.ability & this.AbilityType.MAINSTREAM) {
          streamType = 0;
        }
      } else {
        // 当前窗口跟选中放大的窗口匹配
        if (this.col == this.selectCol && this.row == this.selectRow) {
          if (this.ability & this.AbilityType.MAINSTREAM) {
            streamType = 0;
          } else if (this.ability & this.AbilityType.SUBSTREAM) {
            streamType = 1;
          }
        } else {
          if (this.ability & this.AbilityType.SUBSTREAM) {
            streamType = 1;
          } else if (this.ability & this.AbilityType.MAINSTREAM) {
            streamType = 0;
          }
        }
      }
      return streamType;
    },

    // 切换视频流类型
    switchStreamByType(streamType) {
      // 如果当前没有视频流播放的情况下，直接退出
      if (!this.videoHandler) {
        return;
      }
      this.getStreamUrlAndPlay(this.resid);
    },

    // websocket连接成功
    wsConnectSuccess() {
      this.currentPlayStatus = this.PlayStaus.PLAYING;

      if (this.videoInterval) {
        this.showError = false;
        clearInterval(this.videoInterval);
        this.videoInterval = null;
        this.errorMessage = "";
      }
    },

    // 断线重连, 实时预览下重连, 录像回放不进行重连
    discntAndRecntPlay() {
      if (this.videoInterval) {
        clearInterval(this.videoInterval);
        this.videoInterval = null;
      }

      this.currentPlayStatus = this.PlayStaus.NOTPLAY;

      if (this.currentVideoMode === this.VideoMode.REALPLAY) {
        this.getStreamUrlAndPlay(this.resid);
        this.videoInterval = setInterval(() => {
          this.getStreamUrlAndPlay(this.resid);
        }, this.time);
      }
    },

    // 回放出现异常,重新连接播放
    backRecntAndPlay() {
      this.currentPlayStatus = this.PlayStaus.NOTPLAY;
      this.getFileUrlAndPlay(this.fileid);
    },

    DoRecntAndPlay() {
      if (this.currentVideoMode === this.VideoMode.REALPLAY) {
        this.discntAndRecntPlay();
      } else {
        this.backRecntAndPlay();
      }
    },
    getFileUrlAndPlay(fileid) {
      //   const user = getUser(); //获取用户签名
      const url =
        "http://" +
        user.data.videosvrs[0].ip +
        ":" +
        user.data.videosvrs[0].httpport;

      // const FILE_WEBSOCKET_TYPE = 5;           // 3: ws 5:wss
      const sj = JSON.stringify({
        signature: "", //user.data.signature,  //获取用户签名
        fileid: fileid,
        standardtype: this.protocol
      });
      //   getFileUrl(sj, url).then(res => {
      //     if (res.result === 0) {
      //       if (res.url) {
      //         // res.url ="ws://192.168.0.168:8080/123"
      //         res.url = res.url + '?playtime=' + this.settime;
      //         this.playVideo(res.url);
      //       } else {
      //         this.$message.warning('回放url为空')
      //       }
      //     }
      //   })
    },

    // 获取webrtc视频流并播放
    getStreamUrlAndPlay(resid, callback) {
      console.log("调用了这个函数:",this.playerUrl);
      this.playVideo(this.playerUrl);
    },

    // 获取视频播放的配置
    getConfig() {
      return {
        videoid: this.h5videoid,
        host: this.host,
        camera_view: this.camera_view
      };
    },

    // 设置并返回webrtc视频相关配置属性
    setWebrtcConf(playid, host, camera_view) {
      let conf = {
        videoid: playid,
        host: host,
        camera_view: camera_view
      };
      return conf;
    },

    // 设置并返回websocket视频相关配置属性
    setWebsocketConf(
      playid,
      url,
      camera_view,
      audioEnabled = false,
      recordEnabled = false
    ) {
      const conf = {
        domId: playid,
        url: url,
        codingType: null,
        data: "",
        audioEnabled: true,
        recordEnabled: recordEnabled
      };
      return conf;
    },

    // 处理视频录像的接口给
    handleVideoRecord() {},

    // 暂停或者播放视频流
    handleMute() {
      if (this.videoHandler) {
        const video = document.getElementById(this.h5videoid);
        if (video.paused) {
          video.play();
        } else {
          video.pause();
        }
        this.isStop = !this.isStop;
      }
    },

    // 调整图像的相关参数
    adjustmentVideo(params) {
      this.saturation = (params.saturation * 2.0) / 100;
      this.brightness = (params.brightness * 2.0) / 100;
      this.hue = (params.hue / 50.0) * 360;
      this.contrast = (params.contrast * 2.0) / 100;
      this.setVideoColorParam();
    },

    // 获取视频图像的相关参数
    getVideoColorParam() {
      return {
        saturation: this.saturation * 50,
        hue: (this.hue / 360) * 50,
        brightness: this.brightness * 50,
        contrast: this.contrast * 50
      };
    },

    // 设置视频的相关参数
    setVideoColorParam() {
      const video = document.getElementById(this.h5videoid);
      const filters =
        "saturate(" +
        this.saturation +
        ") hue-rotate(" +
        this.hue +
        "deg) brightness(" +
        this.brightness +
        ") contrast(" +
        this.contrast +
        ")";
      video.style.filter = filters;
    },

    setErrorMessage(name, errorValue) {
      if (errorValue && errorValue in this.ErrorMsgInfo) {
        if (errorValue == this.ErrorMsgType.WSRECONNECT) {
          // 实时预览进行断线重连, 回放时不进行断线重连
          this.discntAndRecntPlay();
        }

        if (errorValue == this.ErrorMsgType.PARSEDATAERROR) {
          // 处理回放解码数据异常时，重新建立连接播放
          this.DoRecntAndPlay();
        }
        this.errorMessage = name + " " + this.ErrorMsgInfo[errorValue];
      } else {
        this.errorMessage = name + " 打开失败 错误码为1";
      }
      console.log("setErrorMessage", this.errorMessage);
      this.showError = true;
    },

    closeVideo(e) {
      this.handleDisConnect();
    },

    capaturePicture() {
      this._capaturePicture();
    },

    // 唯一一个窗口
    fullScreen() {
      this.isFull = !this.isFull;
      this.$emit("do-one-screen", this.row, this.col);
    },

    handleDisConnect() {
      if (this.videoHandler) {
        this.videoHandler.disconnect();
      }

      if (this.videoInterval) {
        this.showError = false;
        clearInterval(this.videoInterval);
        this.videoInterval = null;
        this.errorMessage = "";
      }

      this.currentPosition = 0;
      this.lastestPosition = 0;
      this.currentPlayStatus = this.PlayStaus.NOTPLAY;
      this.fileid = null;
      this.errorMessage = "";
      this.showError = false;
      this.resid = null;
      this.camera_view = null;
      this.videoname = "";
      this.canvasplay = null;
      this.videoHandler = null;
      this.$emit("closed");
    }
  }
};
</script>

<style lang="scss" scoped>
.canh5video {
  width: 100%;
  height: 100%;
}
#showPic{
  /* width: 600px;
  height: 600px; */
  border: solid 2px #00f;
  position: absolute;
  top:0;
  z-index: 99;

}
.error-video {
  width: 100%;
  height: 100%;
  display: flex;
  box-sizing: border-box;
  align-items: center;
  justify-content: center;
  background: black;
  color: white;
  overflow: hidden;
}

.h5video {
  object-fit: fill;
  background: black;
}

.h5canvas {
  width: 100%;
  height: 100%;
  background: black;
}

video {
  width: 100%;
  height: 100%;
  display: flex;
  justify-items: center;
  align-items: center;
  color: white;
}

canvas {
  width: 100%;
  height: 100%;
  display: flex;
  justify-items: center;
  align-items: center;
  color: white;
}

.vidbuttion {
  height: 24px;
  width: 16px;
  padding: 0px;
  margin: 0px;
  margin-left: 5px;
  opacity: 0.9;
  padding: 0 2px;
  color: #ffffff;
  font-size: 18px;
  background: none;
  border: 0;
}
.vidbuttion:hover {
  color: #ffffff !important;
}
.vidbuttion:nth-child(1) {
  /* margin-right: 20px; */
  background: none;
}

.vidbuttion:nth-child(8) {
  background: none;
}


.h5videowrapper {
  position: relative;
  padding: 0px;
  height: 100%;
  width: 100%;
  .operation {
    padding: 5px 10px;
    top: 0;
    right: 0;
    position: absolute;
    z-index: 100;
    // background-color: aqua;
    .operation-item {
      font-size: 12px;
      // background-color: bisque;
      border: 1px solid #fff;
      border-radius: 3px;
      color: #fff;
      padding: 5px;
    }
  }
}

/* 视频按钮背景图片 */
.h5videowrapper > .h5controls {
  position: absolute;
  top: 0px;
  left: 0px;
  background: rgba(0, 0, 0, 0.6);
  padding: 0px;
  box-sizing: content-box;
  z-index: 1000;
  width: 100%;
  height: 28px;
  object-fit: 0.3;
}

.h5videowrapper > .h5controls ul {
  display: inline;
  list-style: none;
}

.h5videowrapper > .h5controls ul .h5video-title {
  display: inline-block;
  color: white;
  font-size: 14px;
  font-family: PingFang SC Semibold, PingFang SC Semibold-Semibold;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

@media screen and (max-width: 1700px) {
  .h5video-title {
    display: inline-block;
    color: white;
    font-size: 14px;
    font-family: PingFang SC Semibold, PingFang SC Semibold-Semibold;
    max-width: 50px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}

.muti-screen {
  margin-top: 4px;
  margin-left: 9px;
  margin-right: 2px;
}

.pull-right {
  float: right !important;
}
</style>